package com.veo.service.Impl;

import com.veo.dao.BlogRespository;
import com.veo.entity.Blog;
import com.veo.entity.BlogQuery;
import com.veo.entity.Tag;
import com.veo.entity.Type;
import com.veo.exception.NotFoundException;
import com.veo.service.BlogService;
import com.veo.service.TagService;
import com.veo.utils.MarkDownUtils;
import com.veo.utils.MyBeanUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogRespository blogRespository;

    @Autowired
    private TagService tagService;

    @Override
    public Blog getBlog(Long id) {
        return blogRespository.getById(id);
    }

    @Transactional
    @Override
    public Blog getAndConvertBlog(Long id) {
        Blog blog = blogRespository.getById(id);
        if (blog == null){
            throw new NotFoundException("博客不存在");
        }
        //将markdown内容转换为html，这里jpa肯会操作数据库，所以要复制属性
        Blog b = new Blog();
        String content = blog.getContent();
        blog.setContent(MarkDownUtils.markdownToHtmlExtensions(content));
        BeanUtils.copyProperties(blog,b);
        blogRespository.updateViews(id);
        return b;
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        //jpa内部条件查询
        Specification<Blog> blogSpecification = new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {
                //构造条件查询的集合
                List<Predicate> predicates = new ArrayList<>();
                //判断查询的参数
                //判断是否输入标题
                if (!"".equals(blog.getTitle()) && blog.getTitle() != null){
                    predicates.add(cb.like(root.<String>get("title"), "%" + blog.getTitle() + "%"));
                }
                //判断是否选择分类
                if (blog.getTypeId() != null){
                    predicates.add(cb.equal(root.<Type>get("type").get("id"), blog.getTypeId()));
                }
                //是否点击推荐
                if (blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommended"), blog.isRecommend()));
                }
                //构造where后面的查询条件
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        };

        //按照分页和构造的条件查询来查询数据
        return blogRespository.findAll(blogSpecification,pageable);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogRespository.findAll(pageable);
    }

    @Override
    public Page<Blog> listBlog(Long tagId, Pageable pageable) {
        return blogRespository.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                //关联查询
                Join join = root.join("tags");
                return cb.equal(join.get("id"),tagId);
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog( String query, Pageable pageable) {
        return blogRespository.findByQuery(query,pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC,"updatedTime");
        Pageable pageable = PageRequest.of(0,size , sort);
        return blogRespository.findTop(pageable);
    }

    @Override
    public Map<String, List<Blog>> archiveBlog() {
        List<String> years = blogRespository.findGroupYear();
        Map<String, List<Blog>> map = new HashMap<>();
        for (String year : years) {
            map.put(year,blogRespository.findByYear(year));
        }
        return map;
    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {

        //id为null 博客新增
        if (blog.getId() == null){
            //博客保存时的初始化参数
            blog.setCreatedTime(new Date());
            blog.setUpdatedTime(new Date());
            blog.setViews(0);
        }else {
            blog.setUpdatedTime(new Date());
        }
        return blogRespository.save(blog);
    }

    @Override
    public Long countBlog() {
        return blogRespository.count();
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {
        Blog b = blogRespository.getById(id);
        if (b == null){
            throw new NotFoundException("不存在该类型的id---updateBlog--id");
        }
        BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdatedTime(new Date());
        return blogRespository.save(b);
    }

    @Transactional
    @Override
    public void deleteBlog(Long id) {
        blogRespository.deleteById(id);
    }
}
